from typing import Any, Union

import cv2

from core.tools.entities.tool_entities import ToolInvokeMessage
from core.tools.errors import ToolInvokeError
from core.tools.tool.builtin_tool import BuiltinTool


class WebcamTool(BuiltinTool):
    def _invoke(
        self,
        user_id: str,
        tool_parameters: dict[str, Any],
    ) -> Union[ToolInvokeMessage, list[ToolInvokeMessage]]:
        """
        invoke tools
        """
        cap = cv2.VideoCapture(0)
        success = cap.isOpened()
        # 关闭自动白平衡
        cap.set(cv2.CAP_PROP_AUTO_WB, 0)
        ret, frame = cap.read()
        if not ret or not success:
            raise ToolInvokeError("Failed to capture image from webcam")
        cap.release()

        result = []

        # for image in response.data:
        _, buffer = cv2.imencode(".jpg", frame)
        result.append(
                self.create_blob_message(
                    blob=buffer.tobytes(),
                    meta={"mime_type": "image/png"},
                save_as=self.VariableKey.IMAGE.value,
            )
        )
        
        return result
